package com.ts.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import com.ts.utils.CSVUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class listJson2CSV {

    //list类型的JSON写入CSV（理论上map一样可写入）
    @SuppressWarnings({ "unchecked" })
    public static void main(String[] args) throws IOException{
        //获取JSON对象
        String jsonStr = getJsonString();
        JSONArray jsonArray =  JSONArray.fromObject(jsonStr);
        //生成list用以写入CSV
        LinkedList<LinkedHashMap<String, String>> exportData = new LinkedList<LinkedHashMap<String, String>>();
        //JSONArray导入list
        for(Iterator<?> it = jsonArray.iterator();it.hasNext();){
            JSONObject jsonObject= (JSONObject) it.next();
            LinkedHashMap<String, String> dataMap = json2Map(jsonObject);
            exportData.add(dataMap);
        }

        //表头
        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        Iterator<?> it = exportData.get(0).entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, String> entry = (Entry<String, String>) it.next();
            String key =  entry.getKey();
            headMap.put(key,key);
        }
        CSVUtils.createCSVFile(exportData, headMap, "C:\\Users\\mlamp\\Desktop\\nanchang\\gongjiao\\", "线路详细信息");//生成CSV文件
    }

    //JSON转换为map
    public static LinkedHashMap<String, String> json2Map(JSONObject jsonObject) throws IOException {
        //转换为map对象
        LinkedHashMap<String, String> dateMap= new LinkedHashMap<String, String>();
        Iterator<?>  iterator = jsonObject.keys();
        while(iterator.hasNext()){
            String	key = (String) iterator.next();
            String value = jsonObject.getString(key);
            dateMap.put(key, value);
        }
        return dateMap;
    }
    //读取文件中的JSON字符串
    @SuppressWarnings("resource")
    private static String getJsonString() throws IOException {
        String filePath = "C:\\Users\\mlamp\\Desktop\\nanchang\\gongjiao\\444444.txt";
        String line = null;
        //定义一个空字符串来接受读到的字符串
        String str="";
        BufferedReader in =  new BufferedReader(new FileReader(filePath));
        //循环把读取到的字符赋给str
        while((line = in.readLine())!=null)
        {
            str+=line;
        }
        return str;
    }

//    public static void main(String[] args) throws IOException {
//
//        String json = getJsonString();
//        List<String> list = new ArrayList<>()
//
//        String[] array1 = json.split("]");
//        for (String a :
//                array1) {
//            String result = a.split("[")[1];
//
//        }
//
//    }
}